package com.zhangxiaofanfan.hotcode.second;

import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * <a href="https://leetcode.cn/problems/longest-consecutive-sequence/?envType=study-plan-v2&envId=top-100-liked">最长连续序列</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-21 08:17:51
 */
public class HotCode003 {
    public static void main(String[] args) {
        // int[] nums = {100,4,200,1,3,2};
        int[] nums = {4,1,3,2};
        HotCode003 hotCode003 = new HotCode003();
        System.out.println(hotCode003.longestConsecutive(nums));

        // 输入：nums = [0,3,7,2,5,8,4,6,0,1]
    }

    public int longestConsecutive(int[] nums) {
        if (nums.length <= 1) {
            return nums.length;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)) {
                continue;
            }
            priorityQueue.add(num);
            set.add(num);
        }
        int result = 1, maxLength = 1;

        while (!priorityQueue.isEmpty()) {
            Integer min = priorityQueue.remove();
            if (!priorityQueue.isEmpty()) {
                maxLength = (priorityQueue.peek() - 1 == min) ? maxLength + 1 : 1;
            }
            result = Math.max(result, maxLength);
        }

        return result;
    }
}
